package com.example.musicplayer.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.musicplayer.R;
import com.example.musicplayer.commonUtils.DisplayUtil;
import com.example.musicplayer.musicClass.MusicMenu;
import com.example.musicplayer.musicTools.MusicListType;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.settings.DesktopLyricSettings;
import com.example.musicplayer.user.User;

public class DesktopMusicMenuListAdapter extends BaseAdapter {
    private final Context mContext;
    private final MusicService.MusicBinder mMusicBinder;
    private final AdapterHandler mHandler;
    private final DesktopLyricSettings mLyricSettings;

    public DesktopMusicMenuListAdapter(Context context, MusicService.MusicBinder musicBinder, DesktopLyricSettings lyricSettings) {
        mContext = context;
        mMusicBinder = musicBinder;
        mLyricSettings = lyricSettings;
        mHandler = new AdapterHandler();
    }

    public void playMusicMenu(int position) {
        if (mMusicBinder != null) {
            if (position == 0) {
                if (mMusicBinder.getFavoriteMusicCounts() > 0 && !mMusicBinder.isPlayingFavoriteList()) {
                    mMusicBinder.start(MusicListType.TYPE_FAVORITE, null, null);
                    notifyDataSetChanged();
                }
            } else {
                MusicMenu playingMenu = mMusicBinder.getPlayingMusicMenu();
                MusicMenu clickedMenu = mMusicBinder.getMusicMenu(position - 1);
                if (clickedMenu != null && clickedMenu.getCounts() > 0) {
                    if (playingMenu == null || playingMenu.getOrder() != clickedMenu.getOrder()) {
                        mMusicBinder.start(MusicListType.TYPE_MENU, clickedMenu, null);
                        notifyDataSetChanged();
                    }
                }
            }
        }
    }

    @Override
    public int getCount() {
        int menuCounts = 1;
        if (mMusicBinder != null) {
            menuCounts += mMusicBinder.getMusicMenuCounts();
        }
        return menuCounts;
    }

    @Override
    public Object getItem(int position) {
        if (mMusicBinder != null && position > 0) {
            return mMusicBinder.getMusicMenu(position - 1);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.desktop_music_menu_list_item, null);
            convertView.setLayoutParams(new ViewGroup.LayoutParams((int) mContext.getResources().getDimension(
                    R.dimen.desktop_music_menu_list_item_width), ViewGroup.LayoutParams.MATCH_PARENT));
            viewHolder.mCover = convertView.findViewById(R.id.music_menu_cover);
            viewHolder.mName = convertView.findViewById(R.id.music_menu_name);
            viewHolder.mMusicMenuNameOfBitmap = "";
            //set outline for image view
            int imageSize = (int) mContext.getResources().getDimension(R.dimen.desktop_music_menu_list_item_image_size);
            int imageRadius = (int) mContext.getResources().getDimension(R.dimen.desktop_music_menu_list_item_image_radius);
            DisplayUtil.setRoundRectOutline(viewHolder.mCover, 0, 0, imageSize, imageSize, imageRadius);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        MusicMenu musicMenu;
        if (position == 0) {
            viewHolder.mName.setText(R.string.desktop_music_menu_favorite);
            viewHolder.mCover.setImageBitmap(User.getInstance().getUserPhoto());
            if (mMusicBinder != null && mMusicBinder.isPlayingFavoriteList()) {
                viewHolder.mName.setTextColor(mLyricSettings.getLyricTextColor());
            } else {
                viewHolder.mName.setTextColor(mContext.getResources().getColor(R.color.desktop_lyric_normal));
            }
        } else if (mMusicBinder != null && (musicMenu = mMusicBinder.getMusicMenu(position - 1)) != null) {
            //update current update music menu
            viewHolder.mMusicMenuName = musicMenu.getName();
            //if need update bitmap after reuse the convertView
            if (!viewHolder.mMusicMenuName.equals(viewHolder.mMusicMenuNameOfBitmap)) {
                //new request to obtain bitmap
                final UpdateCoverRequest request = new UpdateCoverRequest(musicMenu, viewHolder);
                new Thread() {
                    @Override
                    public void run() {
                        Bitmap menuCover = request.getMusicMenu().getBitmap();
                        request.setBitmap(menuCover);
                        Message msg = mHandler.obtainMessage();
                        msg.obj = request;
                        mHandler.sendMessage(msg);
                    }
                }.start();
            }
            //set music menu name
            viewHolder.mName.setText(viewHolder.mMusicMenuName);
            //set text color
            MusicMenu playingMenu = mMusicBinder.getPlayingMusicMenu();
            if (playingMenu != null && (position - 1) == playingMenu.getOrder()) {
                viewHolder.mName.setTextColor(mLyricSettings.getLyricTextColor());
            } else {
                viewHolder.mName.setTextColor(mContext.getResources().getColor(R.color.desktop_lyric_normal));
            }
        }
        return convertView;
    }

    private static class AdapterHandler extends Handler {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof UpdateCoverRequest) {
                UpdateCoverRequest request = (UpdateCoverRequest) msg.obj;
                //judge if the current viewHolder is the target for music menu
                if (request.getMusicMenu().getName().equals(request.getTarget().mMusicMenuName)) {
                    Bitmap bitmap = request.getBitmap();
                    if (bitmap != null) {
                        request.getTarget().mCover.setImageBitmap(bitmap);
                        request.getTarget().mMusicMenuNameOfBitmap = request.getMusicMenu().getName();
                    }
                }
            }
        }
    }

    private static class UpdateCoverRequest {
        private final MusicMenu mMusicMenu;
        private final ViewHolder mTarget;
        private Bitmap mBitmap;

        public UpdateCoverRequest(MusicMenu musicMenu, ViewHolder targetViewHolder) {
            mMusicMenu = musicMenu;
            mTarget = targetViewHolder;
        }

        public MusicMenu getMusicMenu() {
            return mMusicMenu;
        }

        public ViewHolder getTarget() {
            return mTarget;
        }

        public Bitmap getBitmap() {
            return mBitmap;
        }

        public void setBitmap(Bitmap bitmap) {
            mBitmap = bitmap;
        }
    }

    private static class ViewHolder {
        String mMusicMenuName;
        //if not set bitmap, null. if has bitmap, it is the menu name of which bitmap
        String mMusicMenuNameOfBitmap;
        ImageView mCover;
        TextView mName;
    }
}